package org.hibernate.tutorial.hello.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.tutorial.hello.domain.Message;
import org.hibernate.tutorial.util.HibernateUtil;

public class MessageDao {
	
	/**
	 * 保存消息
	 * @param message	消息对象
	 * @return	保存后的id
	 */
	public Long save(Message message){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		Long id = (Long) session.save(message);
		
		session.getTransaction().commit();
		
		return id;
	}
	
	/**
	 * 取得所有消息
	 * @return	消息列表
	 */
	@SuppressWarnings("unchecked")
	public List<Message> getMessages(){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		List<Message> messages = session.createQuery("from Message m order by m.text asc").list();
		
		session.getTransaction().commit();
		
		return messages;
	}
}
